package txt2vz;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;


@SuppressWarnings("serial")
public class TwitServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		String strCallResult = "";
		resp.setContentType("text/plain");
		
		JSONObject js;
		
		try {
			// Extract out the user entered ISBN number
			String qTwit = req.getParameter("q");
			
			System.out.println("in twitservet q: " +qTwit);

		// Do basic validation
			if (qTwit == null)
				throw new Exception("query field cannot be null");

			// Trim
			qTwit = qTwit.trim();
			if (qTwit.length() == 0)
				throw new Exception("query field cannot be empty");
			qTwit = qTwit.replace(" ", "%20");
			qTwit= qTwit+"&rpp=100";
			System.out.println("in twitservet q2 : " +qTwit);
			
			String strTwit = "http://search.twitter.com/search.json?q="+qTwit;	
			System.out.println("in twitservet q3 : " +strTwit);

			URL twiturl = new URL(strTwit);		
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(					
					twiturl.openStream()));
			StringBuffer sb = new StringBuffer();
			String line;

			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			reader.close();
			
			
			JSONObject jsonObj = (JSONObject) JSONValue.parse(sb.toString());

			JSONArray twArray = (JSONArray) jsonObj.get("results");		
			
			StringBuffer sb2 = new StringBuffer();

			for (int i = 0; i < twArray.size(); i++) {
				JSONObject tx = (JSONObject) JSONValue.parse(twArray.get(i)
						.toString());
				sb2.append(tx.get("text"));
				System.out.println("tx " + i + " " + tx.get("text"));
			}			

			strCallResult = sb2.toString();

			resp.getWriter().println(strCallResult);

		} catch (Exception ex) {
			strCallResult = "Error: " + ex.getMessage();
			resp.getWriter().println(strCallResult);
		}
	}

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
}

